<template>
  <div class="ma-content-block lg:flex justify-between p-4">
    <ma-crud :options="options" :columns="columns" ref="crudRef">
      <template #id="{ record }">
        <a-link color="blue" @click="editAction(record)">{{ record.id }}</a-link>
      </template>
      <template #tableButtons>
        <slot name="tableButtons">
          <a-button
          @click="openDictList()" type="primary"
          class="w-full lg:w-auto mt-2 lg:mt-0"
          v-auth="['finance:bonusPercentageBill:save']"
            >
              <template #icon>
                <icon-plus/>
              </template>
              创建提成单
            </a-button>
            <download url="finance/bonusPercentageBill/export" type="bonusPercentageBill" :auth="['finance:bonusPercentageBill:export']"/>
        </slot>
      </template>
      <template #beforeTable>
        <button-group :button-groups="buttonGroups" :crud-ref="crudRef" :selected="selected" :currentStatus="currentStatus" />
        <!-- <a-button @click="exportList()" size="small" type="primary" v-auth="['finance:bonusPercentageBill:export']">
          <template #icon>
            <icon-download/>
          </template>
          账单流水（模板）
        </a-button> -->
      </template>
    </ma-crud>
    <batch-action-modal v-model="batch.visible"
    :crud-ref="crudRef"
    :selected="selected"
    ref="batchActionRef"
    ></batch-action-modal>
    <data-list ref="datalist"  @child-event="addAction" />
    <bill-info ref="billInfo" />
    <add-modal ref="addModalRef"></add-modal>
  </div>
</template>
<script setup>
import {ref, reactive, provide, computed} from 'vue'
import bonusPercentageBill from '@/api/finance/bonusPercentageBill'
import BatchActionModal from "@cps/actions/batchActionModal.vue";
import DataList from './components/create.vue'
import BillInfo from './billInfo.vue'
import ButtonGroup from "@cps/actions/buttonGroup.vue";
import dicthelper from "@/utils/dicthelp.js";
import AddModal from "@cps/actions/addModal.vue";
import {Message} from '@arco-design/web-vue'
import Download from "@/views/components/download.vue";
const crudRef = ref()
const addModalRef = ref()
const batchActionRef = ref()
const batch = ref({visible:false,})
const selected = computed(()=>crudRef.value?.selecteds)
const billInfo = ref()
const datalist = ref()
const currentStatus = computed(() => {
  if (!crudRef.value) {
    return null
  }
  let requestParams = crudRef.value.requestParams
  if (!requestParams.status) {
    return null;
  }
  return requestParams.status
})
const getDictData = (key, value) => {
  let label = ''
  let dict = crudRef.value?.getColumnService().dicts[key];
  if(dict !== undefined && dict.length > 0){
        dict.map(i => {
          if (value == i.value) {
            label = i.label
          }
        })
  }
  return label
}

const exportList = async () =>{
  if(selected.value.length == 0){
    Message.error('选择要导出的账单')
    return
  }
  addModalRef.value.open(reactive([
      {
        title: "确认导出吗",
        formType: "static-text",
        dataIndex: "deduction",
      },
      {
        title: "",
        formType: "select",
        dataIndex: "ids",
        multiple:true,
        addDefaultValue:selected.value,
        // addDisplay:false
      },
    ]) , {
         viewType: 'modal',
      }, bonusPercentageBill.exportTemplate,'导出',)
}

const buttonGroups = [
  {title:'审计',api:bonusPercentageBill.auditPass,displayDataIndex:"id",auth:['finance:bonusPercentageBill:audit'],
  hideStatus: ['2','3']
  },
  {title:'反审计',api:bonusPercentageBill.auditRefuse,displayDataIndex:"id",auth:['finance:bonusPercentageBill:audit'],
  hideStatus: ['1','3']
  },
  {title:'删除',api:bonusPercentageBill.deletes,displayDataIndex:"id",auth:['finance:bonusPercentageBill:delete'],
    status:'danger',hideStatus: ['2','3']
  },
    // todo 待开发
  // {title:'核销',
  //
  // },
  // {title:'查看统计',displayDataIndex:"id",
  //
  // },
  // {title:'导出',displayDataIndex:"id",
  // },
]

let isAdd = false

const getDefaultDate = (type)=> {
  let CurrentDate = new Date();
  if(type == 1){
    CurrentDate.setDate(CurrentDate.getDate()); // 设置为第二天
  }else{
    CurrentDate.setDate(CurrentDate.getDate() + 1); // 设置为第二天
    CurrentDate.setHours(23, 59, 59, 0);
  }
  return CurrentDate.toISOString().slice(0, 19).replace('T', ' ')
}

const addAction = async (data) => {
  columns.map((item)=>{
    console.log(item)
    item.addDefaultValue = data[item.dataIndex] ? data[item.dataIndex] : data.user[item.dataIndex]
    if(!['user_id','currency','amount','bill_type','bill_data'].includes(item.dataIndex)){
        item.disabled = false
      }
    if(item.dataIndex == 'bill_date'){
      item.addDefaultValue = getDefaultDate(1)
    }  
    if(item.dataIndex == 'expire_date'){
      item.addDefaultValue = getDefaultDate(2)
    }  
  })
  crudRef.value.addAction()
}

const editAction = (record) =>
{
   isAdd = false
   columns.map((item)=>{
    if(!['memo','check_memo','expire_action'].includes(item.dataIndex)){
      item.disabled = record.status > 1
    }
    if(['user_id','currency','amount','bill_type','bill_data'].includes(item.dataIndex)){
        item.disabled = true
      }
   })
   crudRef.value.editAction(record)
}

const openDictList = async (row) => {
    isAdd = true
    datalist.value.open(row)
  }

const options = reactive({
  id: 'bonus_percentage_bill',
  pageLayout: 'fixed',
  rowSelection: {
    showCheckedAll: true
  },
  afterRequest: (tableData) => {
    if(isAdd){
      datalist.value.requestData()
    }
    return tableData
  },
  tabs:{
    dataIndex: "status"
  },
  pk: 'id',
  // operationColumn: true,
  // operationColumnWidth: 160,
  formOption: {
    viewType: 'drawer',
    width: "60%",
    layout: [{
        formType: 'grid-tailwind',
        colNumber: 1,
        cols: [
          {
            formList: [
              {dataIndex: "user_id"},
              // {dataIndex: "bill_number"},
              {dataIndex: "currency"},
              {dataIndex: "bill_date"},
              {dataIndex: "expire_date"},
              // {dataIndex: "expire_action"},
              {dataIndex: "bill_type"},
              {dataIndex: "bill_data"},
            ]
          }
        ]
      }]
  },
  api: bonusPercentageBill.getList,
  recycleApi: bonusPercentageBill.getRecycleList,
  add: {
    show: false,
    api: bonusPercentageBill.save,
    auth: ['finance:bonusPercentageBill:save'],
    
  },
  edit: {
    show: true,
    api: bonusPercentageBill.update,
    auth: ['finance:bonusPercentageBill:update'],
    action: (record)=>{
      billInfo.value.open(record)
    }
  },
  afterEdit: ()=>{
    billInfo.value.refreshRecode()
  },
  delete: {
    show: true,
    api: bonusPercentageBill.deletes,
    auth: ['finance:bonusPercentageBill:delete'],
    realApi: bonusPercentageBill.realDeletes,
    realAuth: ['finance:bonusPercentageBill:realDeletes']
  },
  recovery: {
    show: true,
    api: bonusPercentageBill.recoverys,
    auth: ['finance:bonusPercentageBill:recovery']
  },
  export: {
    show: true,
    url: 'finance/bonusPercentageBill/export',
    auth: ['finance:bonusPercentageBill:export']
  }
})
const columns = reactive([
  {
    title: "主键",
    dataIndex: "id",
    formType: "input",
    addDisplay: false,
    editDisplay: false,
    hide: true,
    commonRules: {
      required: true,
      message: "请输入主键"
    }
  },
  {
    title: "账单号",
    dataIndex: "id",
    formType: "input",
    search: true
  },
  {
    title: "销售",
    dataIndex: "user_id",
    disabled:true,
    formType: "select",
    dict: dicthelper.user,
    search: true
  },
  {
    title: "币种",
    dataIndex: "currency",
    dict: {
      name: "currencyType",
      props: {
        label: "title",
        value: "key"
      },
      translation: true
      },
    disabled:true,
    formType: "select"
  },
  {
    title: "账单金额",
    dataIndex: "amount",
    disabled:true,
    formType: "input"
  },
  {
    title: "流水总额",
    dataIndex: "statement_amount",
    addDisplay: false,
    editDisplay: false,
    formType: "input",
    hide: true
  },
  {
    title: "已支付",
    dataIndex: "audit_amount",
    addDisplay: false,
    editDisplay: false,
    formType: "input"
  },
  {
    title: "余款",
    dataIndex: "unaudit_amount",
    addDisplay: false,
    editDisplay: false,
    formType: "input"
  },

  {
    title: "账户id",
    dataIndex: "account_id",
    addDisplay: false,
    editDisplay: false,
    formType: "input",
    hide: true
  },
  // {
  //   title: "到期动作",
  //   dataIndex: "expire_action",
  //   dict: {
  //     name: "SupplierBillDo",
  //     props: {
  //       label: "title",
  //       value: "key"
  //     },
  //     translation: true
  //     },
  //   formType: "checkbox"
  // },
  {
    title: "创建者",
    dataIndex: "created_by",
    formType: "select",
    dict: {
        url: 'system/user/list',
        props: {label: 'nickname', value: 'id'} ,
        params: {select: 'id,nickname'},
        translation: true,
      }, 
    addDisplay: false,
    editDisplay: false,
  },
  {
    title: "备注",
    dataIndex: "memo",
    // addDisplay: false,
    // editDisplay: false,
    formType: "textarea"
  },
  {
    title: "状态",
    dataIndex: "status",
    dict: {
      name: "BillStatus",
      props: {
        label: "title",
        value: "key"
      },
      translation: true
      },
    formType: "select",
    search: true,
    addDisplay: false,
    editDisplay: false,
    hide:true
  },
  {
        title: "账单流水类型",
        dataIndex: "bill_type",
        formType: "radio",
        disabled:true,
        addDefaultValue:1,
        editDisplay: false,
        dict: {
            name: "FinancialStatementType",
            props: {
                label: "title",
                value: "key"
            },
        translation: true
        },
        hide:true,
    },
    {
        title: "业务时间",
        dataIndex: "bill_data",
        editDisplay: false,
        formType: "range",
        disabled:true,
        search:true,
        hide:true,
    },
  {
    title: "账单时间",
    dataIndex: "bill_date",
    formType: "date",
    search: true,
    showTime: true
  },
  {
    title: "到期时间",
    dataIndex: "expire_date",
    formType: "date",
    hide: true,
    showTime: true
  },
  {
    title: "结算方式",
    dataIndex: "pay_type",
    addDisplay: false,
    editDisplay: false,
    dict: {
      name: "settlement",
      props: {
        label: "title",
        value: "key"
      },
      translation: true
      },
    formType: "select",
    search: true,
    hide:true
  },
  {
    title: "核销时间",
    dataIndex: "checked_at",
    formType: "date",
    addDisplay: false,
    editDisplay: false,
    showTime: true
  },
  {
    title: "审核备注",
    dataIndex: "check_memo",
    formType: "textarea",
    // addDisplay: false,
    // editDisplay: false,
    hide: true,
  },
  {
    title: "更新者",
    dataIndex: "updated_by",
    formType: "input",
    addDisplay: false,
    editDisplay: false,
    hide: true
  },
  {
    title: "创建时间",
    dataIndex: "created_at",
    formType: "date",
    addDisplay: false,
    editDisplay: false,
    showTime: true
  },
  {
    title: "更新时间",
    dataIndex: "updated_at",
    formType: "date",
    addDisplay: false,
    editDisplay: false,
    hide: true,
    showTime: true
  },
  {
    title: "删除时间",
    dataIndex: "deleted_at",
    formType: "date",
    addDisplay: false,
    editDisplay: false,
    hide: true,
    showTime: true
  },
  {
    title: "备注",
    dataIndex: "remark",
    formType: "input",
    addDisplay: false,
    editDisplay: false,
    hide: true
  }
])
provide('getDictData', getDictData)
provide('crudRef',crudRef)
</script>
<script> export default { name: 'finance:bonusPercentageBill' } </script>